package com.dzl.card.service.impl;

import com.dzl.asynthread.SyncInitDataServiceImpl;
import com.dzl.base.service.BaseServiceImpl;
import com.dzl.card.dao.WelfareCardMapper;
import com.dzl.card.pojo.WelfareCard;
import com.dzl.card.pojo.WelfareCardSecret;
import com.dzl.card.pojo.query.WelfareCardQuery;
import com.dzl.card.pojo.vo.WelfareCardVo;
import com.dzl.card.service.WelfareCardSecretService;
import com.dzl.card.service.WelfareCardService;
import com.dzl.card.service.WelfareCardTypeService;
import com.dzl.config.database.Master;
import com.dzl.config.exception.CommonException;
import com.dzl.util.DateUtil;
import com.dzl.util.EmptyUtils;
import com.dzl.util.ImageUtils;
import com.dzl.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.IntStream;

/**
 * 福利卡管理(WelfareCard)表服务实现类
 *
 * @author caobucao
 * @since 2021-05-19 09:57:48
 */
@Slf4j
@Service("welfareCardService")
public class WelfareCardServiceImpl extends BaseServiceImpl<WelfareCard> implements WelfareCardService {

    @Autowired
    private WelfareCardMapper mapper;
    @Autowired
    private WelfareCardSecretService welfareCardSecretService;
    @Autowired
    private WelfareCardTypeService welfareCardTypeService;
    @Autowired
    private SyncInitDataServiceImpl syncInitDataServiceImpl;

    @Override
    public PageInfo<WelfareCardVo> selectCardVoListPage(WelfareCardQuery query) {
        PageHelper.startPage(query);
        List<WelfareCardVo> list = mapper.selectCardVoListPage(query);
        if(EmptyUtils.isNotEmpty(list)) {
            list.forEach(x -> {
                if(EmptyUtils.isNotEmpty(x.getImg())) {
                    x.setImg(ImageUtils.setImageSrc(x.getImg()));
                }
                Integer countIsBind = 0;//绑定数，数据库查
                Integer countIsNotBind = 0;//未绑定数 ，实际就等于已激活数，通过数据库查
                Integer countIsActive = 0;//已激活 = 已绑定+未绑定数
                Integer countFrozen = 0; //已冻结
                countIsBind = x.getCountIsBind();
                countIsNotBind = x.getCountIsActivate();
                countIsActive = countIsBind + countIsNotBind;
                x.setCountIsBind(countIsBind);
                x.setCountIsNotBind(countIsNotBind);
                x.setCountIsActivate(countIsActive);
            });
        }
        PageInfo<WelfareCardVo> page = new PageInfo<WelfareCardVo>(list);
        return page;
    }


    @Override
    @Master
    @Transactional(rollbackFor = Exception.class)
    public Integer saveWelfareCard(WelfareCard welfareCard) {
        if(EmptyUtils.isEmpty(welfareCard.getId())) {
            //通过福利卡所属类型查询该类型所属分区
            List<Integer> partitionIdList = welfareCardTypeService.selectPartitionIdByCardTypeId(welfareCard.getCardTypeId());
            if(CollectionUtils.isEmpty(partitionIdList)) {
                throw new CommonException("所选卡类型未关联分区");
            }
            //取该批次卡的批次号数据，K+创建年月日时分秒+6位随机数字
            String batchNumber =StringUtil.getBatchNumber("K");
            welfareCard.setBatchNumber(batchNumber);
            mapper.insertSelective(welfareCard);
            //添加完卡之后，生成卡号卡密
            Integer quantity = welfareCard.getQuantity();
            List<WelfareCardSecret> welfareCardSecretList = new ArrayList<>();
            //获取当前年份的后两位
            String year = DateUtil.getYear().substring(2);
            //查询当前年份的卡总数
            Integer countYearCard = welfareCardSecretService.selectCountYearCard("K"+year);
            IntStream.range(0,quantity).forEach(i -> {
                WelfareCardSecret secret = new WelfareCardSecret();
                secret.setCardId(welfareCard.getId());
                secret.setNumber("K"+year+String.format("%06d", countYearCard+i+1));
                secret.setSecret("FL"+StringUtil.getRandomStringHaveNumberAndEnglishUpperRemoveIO10(14));
                secret.setUpdater(welfareCard.getCreater());
                secret.setUpdaterName(welfareCard.getCreaterName());
                secret.setCreater(welfareCard.getCreater());
                secret.setCreaterName(welfareCard.getCreaterName());
                secret.setCreateTime(new Date());
                secret.setUsedAmount(new BigDecimal("0.00"));
                welfareCardSecretList.add(secret);
            });
            Integer result = welfareCardSecretService.insertList(welfareCardSecretList);
            if(result>0 && EmptyUtils.isNotEmpty(welfareCardSecretList)){
                if(welfareCardSecretList.size()==1){
                    syncInitDataServiceImpl.saveWelfareCardSecretQrcode(welfareCardSecretList);
                }else{
                    List<WelfareCardSecret> list = new ArrayList<>();
                    for(int i=0;i<welfareCardSecretList.size();i++){
                        list.add(welfareCardSecretList.get(i));
                        if(i>0 && (i % 100 == 0 || i == welfareCardSecretList.size()-1)){
                            log.info("=============================================i:"+i+",listSize:"+list.size());
                            syncInitDataServiceImpl.saveWelfareCardSecretQrcode(list);
                            list = new ArrayList<>();
                        }
                    }
                }
            }
            return result;
        }
        return 0;
    }

    @Override
    public Integer updateCardName(WelfareCard welfareCard) {
        Integer countName = mapper.selectCountByName(welfareCard);
        if(countName > 0) {
            throw new CommonException("名称已存在，请更换后重试");
        }
        return mapper.updateByPrimaryKeySelective(welfareCard);
    }

}
